﻿using System.IO;
using System.Windows;
using System.Xml.Serialization;
using CodeBadger.GasMileage.Models;
using CodeBadger.GasMileage.Persistence;

namespace CodeBadger.GasMileage.ViewModels
{
    public class EmailViewModel : ViewModel
    {
        public string EmailAddress { get; set; }

        public bool SendEmail()
        {
            if (!CanFindInternet()) return false;

            var client = new Web.Export.ExportServiceClient();
            try
            {
                const string token = "{secret}";
                client.EmailDataAsync(token, EmailAddress, GetData());
                return true;
            }
            catch
            {
                client.Abort();
                return false;
            }
        }

        private static bool CanFindInternet()
        {
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show("No internet connection is available.  Please try again later");
            }
            return true;
        }

        private string GetData()
        {
            var serializer = new XmlSerializer(typeof(Notebook));
            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, CurrentApp.UserNotebook);
                var utf16Data = writer.ToString();
                var utf8Data = utf16Data.Replace("utf-16", "utf-8");
                return utf8Data;
            }
        }
    }
}
